package com.iddaa.core.service.impl;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Collection;

import net.spy.memcached.MemcachedClient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.iddaa.core.annotation.Memcached;
import com.iddaa.core.annotation.MemcachedRead;
import com.iddaa.core.dao.PersonDAO;
import com.iddaa.core.domain.Person;
import com.iddaa.core.service.PersonService;
import com.iddaa.core.service.SolrService;
import com.iddaa.core.util.Constants;

@Service("personService")
@Memcached(prefix = "Person", expiration = Constants.Cache.PERSON_EXPIRETIME)
public class PersonServiceImpl implements PersonService {

	@Autowired
	private PersonDAO personDAO;

	@Autowired
	private SolrService solrService;

	@Override
	public void deletePerson(Long id) {
		personDAO.delete(findById(id));
		solrService.updateSolr(id,"Person");
		deleteCache(id);
	}

	@Override
	@MemcachedRead
	public Person findById(Long id) {
		return personDAO.getById(id);
	}

	@Override
	public Collection<Person> loadAll() {
		return personDAO.loadAll();
	}

	@Override
	public void savePerson(Person person) {
		personDAO.saveOrUpdate(person);
		solrService.updateSolr(person.getId(), person.getName(), "Person");
		evictCache(person);
	}

	@Async
	public void evictCache(Person person) {
		MemcachedClient memcachedClient = null;
		try {
			memcachedClient = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
			memcachedClient.set("Person:" + person.getId(), Constants.Cache.PERSON_EXPIRETIME, person);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Async
	public void deleteCache(Long id) {
		MemcachedClient memcachedClient = null;
		try {
			memcachedClient = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
			memcachedClient.delete("Person:" + id);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
